package com.xomily.web.core.config;

import com.xomily.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhongshiyu
 * @date 2025/4/6
 */
@Configuration
@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public class NetFilterConfig {

    @Value("${rate.limit}")
    private int rateLimit;
    @Value("${rate.window-time}")
    private long windowSize;
    @Value("${xss.urlPatterns}")
    private String urlPatterns;

    @Bean
    public FilterRegistrationBean<SqlInjectionFilter> sqlInjectionFilterRegistration() {
        FilterRegistrationBean<SqlInjectionFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new SqlInjectionFilter());
        registration.addUrlPatterns(StringUtils.split("/system/*,/monitor/*,/tool/*", ","));
        registration.setName("sqlInjectionFilter");
        registration.setOrder(1); // 设置过滤器的执行顺序
        return registration;
    }

    @Bean
    public FilterRegistrationBean<RateLimitFilter> rateLimitFilterRegistration() {
        FilterRegistrationBean<RateLimitFilter> registration = new FilterRegistrationBean<>();
        RateLimitFilter filter = new RateLimitFilter();
        registration.setFilter(filter);
        registration.addUrlPatterns("/captchaImage/*"); // 拦截所有请求
        registration.setName("rateLimitFilter");
        registration.setOrder(1); // 设置过滤器的执行顺序
        return registration;
    }

    @Bean
    public FilterRegistrationBean<XSSNewFilter> xssFilterRegistration() {
        FilterRegistrationBean<XSSNewFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new XSSNewFilter());
        registration.addUrlPatterns("/*"); // 拦截所有请求
        registration.setName("XSSNewFilter");
        registration.setOrder(1); // 设置过滤器的执行顺序
        return registration;
    }
}
